<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class CateController extends Controller
{
    //add
    public function add()
    {
    	return view('admin.cate.add');
    }

    //insert
    public function insert(Request $request)
    {

        $this -> validate($request, [
            'type' => 'required',
            'name' => 'required',
            'time' => 'required',
            'path' => 'required',
            'pid' => 'required',
            'photo' => 'required',
            'cast' => 'required',
            'director' => 'required',
            'scriptwriter' => 'required',
            'timelong' => 'required',
            'publish' => 'required',
            'synopsis' => 'required'
            ],[
            'type.required' => '请选择类型',
            'name.required' => '请输入电影名',
            'time.required' => '请输入电影年代',
            'path.required' => '请选择电影地区',
            'pid.required' => '请选择电影类型',
            'photo.required' => '请上传海报',
            'cast.required' => '请填写电影团队',
            'director.required' => '请填写电影团队',
            'scriptwriter.required' => '请填写电影团队',
            'timelong.required' => '请填写电影团队',
            'publish.required' => '请填写电影团队',
            'synopsis.required' => '请填写电影团队'
            ]);

    	$data = $request -> except('_token');

        if ($request -> file('photo') -> isValid())
        {
            $file = $request -> file('photo');
            //允许的mime类型
            $allowMime = array('image/jpeg','image/png','image/gif','image/jpg');
            //获取文件mime类型
            $mime = $file -> getMimeType();
            //判断是否允许
            if(in_array($mime,$allowMime))
            {
                //文件后缀名
                $type = $file -> getClientOriginalExtension($file);
                //文件新名字
                $newName = md5(rand(10000,99999)).time().'.'.$type;
                //保存文件
                $file -> move('./home/images/poster/', $newName);
                
                //存入文件新名字
                $data['photo'] = '/home/images/poster/'.$newName;
                $data['pid'] = implode(',', $data['pid']);
                //存入数据库
                $res = DB::table('types') -> insert($data);

                if($res)
                {
                    return redirect('/admin/cate/index') -> with(['info' => '添加成功']);
                }else
                {
                    return back() -> with(['info' => '添加失败']);
                }

            }else
            {
                return back() -> with(['info' => '上传文件失败']);
            }
            
        }else
        {
            return back() -> with(['info' => '上传文件失败']);
        }
        

    }

    //index
    public function index(Request $request)
    {

        $num = $request -> input('num', 15);
        // 查询数据库
        $data = DB::table('types') 
            -> where(function($query) use ($request){
                $query 
            -> where('name', 'like', '%'.$request -> input('keyword').'%');
        })
            ->orderBy('time', 'desc')
            -> paginate($num);

    	return view('admin.cate.index', ['data' => $data, 'request' => $request -> all()]);
    }

    //edit
    public function edit($id)
    {
    	//查询当前
    	$data = DB::table('types')
    	-> where ('id', $id)
    	-> first();
        $data -> pid = explode(',',$data -> pid);
    	return view('admin.cate.edit', ['data' => $data]);
    }

    //update
    public function update(Request $request)
    {
    	$this -> validate($request, [
    		'name' => 'required'
    		],[
    		'name.required' => '电影名称不能为空'
    		]);
    	$data = $request -> except('_token');

        //判断是否上传图片
        if($request -> hasFile('photo'))
        {
            if ($request -> file('photo') -> isValid())
            {
                $file = $request -> file('photo');
                //允许的mime类型
                $allowMime = array('image/jpeg','image/png','image/gif','image/jpg');
                //获取文件mime类型
                $mime = $file -> getMimeType();
                //判断是否允许
                if(in_array($mime,$allowMime))
                {
                    //文件后缀名
                    $type = $file -> getClientOriginalExtension($file);
                    //文件新名字
                    $newName = md5(rand(10000,99999)).time().'.'.$type;
                    //保存文件
                    $file -> move('./home/images/poster/', $newName);
                    
                    //存入文件新名字
                    $data['photo'] = './home/images/poster/'.$newName;
                    $data['pid'] = implode(',', $data['pid']);
                    //存入数据库
                    $res = DB::table('types') -> where('id', $data['id']) -> update($data);

                    if($res)
                    {
                        return redirect('/admin/cate/index') -> with(['info' => '修改成功']);
                    }else
                    {
                        return back() -> with(['info' => '修改失败']);
                    }

                }else
                {
                    return back() -> with(['info' => '上传文件失败']);
                }
                
            }else
            {
                return back() -> with(['info' => '上传文件失败']);
            }
        }else
        {
            //没有上传图片的情况
            $data['pid'] = implode(',', $data['pid']);
            $res = DB::table('types') -> where('id', $data['id']) -> update($data);
            if($res)
            {
                return redirect('/admin/cate/index') -> with(['info' => '修改成功']);
            }else
            {
                return back() -> with(['info' => '修改失败']);
            }
        }
    }

    //删除电影
    public function delete($id)
    {
		DB::table('post') -> where('pid', $id) -> delete();

            $rew = DB::table('types') -> where('id', $id) -> delete();
            if($rew)
            {
                return back() -> with(['info' => '删除成功']);
		    }else
            {
                return back() -> with(['info' => '删除失败']);
            }
    }

    //修改状态

    public function ajaxUpdate(Request $request)
    {
    	$id = $request -> input('id');

    	$data = DB::table('cate') -> where('id', $id) -> first();
    	if($data -> status == '0')
    	{
    		$res = DB::table('cate') ->  where('id', $id) -> update(['status' => '1']);
    		if($res)
    		{
    			return response() -> json(0);
    		}else
    		{
    			return response() -> json(1);
    		}

    	}else
    	{
    		$res = DB::table('cate') -> where('id', $id) -> update(['status' => '0']);
    		if($res)
    		{
    			return response() -> json(2);
    		}else
    		{
    			return response() -> json(3);
    		}
    	}

    }

    //发表影评页
    public function post($id)
    {
        //查询当前
        $data = DB::table('types')
        -> where ('id', $id)
        -> first();

        return view('admin.cate.post',['data' => $data]);
    }

    public function postPublish(Request $request)
    {

        date_default_timezone_set('PRC');

        $this -> validate($request, 
        [
            'total' => 'required',
            'content' => 'required|max:600'
        ]); 

        $data    = $request -> except('_token');
        $total   = $data['total'];
        $score   = $data['total'];
        $pid     = $data['pid'];
        $auth    = $data['auth'];
        $uid     = $data['uid'];
        $content = $data['content'];
        $ctime   = date('Y-m-d H:i:s', time());
        
        
        $res = DB::table('post') -> where('pid', $pid) -> insert(['pid' => $pid, 'uid' => $uid, 'auth' => $auth, 'content' => $content, 'ctime' => $ctime, 'score' => $score]);
        if($res)
        {
            // 查询旧的电影总分数
            $oldTotal = DB::table('types') -> where('id', $pid) -> first() -> total;
            // 计算电影新的总分数
            $newTotal = $oldTotal + $total;
            // 查询本电影总评论条数
            $comments = DB::table('post') -> where('pid', $pid) -> count();
            // 计算电影平均分数
            $score = round($newTotal / $comments, 1);
            $totalRes = DB::table('types') -> where('id', $pid) -> update(['total' => $newTotal, 'score' => $score]);
            if($totalRes)
            {
                return redirect('/admin/post/index/'.$pid) -> with(['info' => '发表成功']);
            }else
            {
                return back() -> with(['info' => '发表失败']);
            }
        }else
        {
            return back() -> with(['info' => '发表失败']);
        }

    }

}
